package com.igeek.yygh;

/**
 * TODO
 *
 * @author Guzhenghui
 * @since 2024/8/26
 */
public class DistanceCalculator {
    private static final double EARTH_RADIUS = 6371; // 地球半径，单位为公里

    public static double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
        // 将经纬度转换为弧度
        double lon1Rad = Math.toRadians(lon1);
        double lat1Rad = Math.toRadians(lat1);
        double lon2Rad = Math.toRadians(lon2);
        double lat2Rad = Math.toRadians(lat2);

        // 计算经度和纬度的差值
        double dLon = lon2Rad - lon1Rad;
        double dLat = lat2Rad - lat1Rad;

        // Haversine公式
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                        Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        // 计算距离
        return EARTH_RADIUS * c*1000;
    }

    public static void main(String[] args) {
        double lon1 = 120.40327, lat1 = 31.497639;
        double lon2 = 120.371091, lat2 = 31.487928;
        double distance = calculateDistance(lon1, lat1, lon2, lat2);
        System.out.println("Distance: " + distance + " m");
    }
}